<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-alert
        title="注意:只允许为第三级分类设置相关参数！"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <el-row class="cat_class"
        ><el-col>
          <span>选择商品分类: </span>
          <!-- 选择商品分类级联选择框 -->
          <el-cascader
            v-model="selectKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
          >
          </el-cascader> </el-col
      ></el-row>
      <!-- 商品分类管理页签 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogFormVisible = true"
            >添加参数</el-button
          >
          <el-table :data="manyTableData" style="width: 100%" border>
            <el-table-column type="expand">
              <!-- 展开列模板渲染模板 -->
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(item, i) in scope.row.attr_vals"
                  closable
                  @close="handleClose(scope.row, i)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editParams(scope.row.attr_id)"
                ></el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row.attr_id)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogFormVisible = true"
            >添加属性</el-button
          >
          <el-table :data="onlyTableData" style="width: 100%" border>
            <el-table-column type="expand">
              <!-- 静态属性展开列 -->
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(item, i) in scope.row.attr_vals"
                  closable
                  @close="handleClose(scope.row, i)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editParams(scope.row.attr_id)"
                ></el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row.attr_id)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数/属性对话框 -->
    <el-dialog
      :title="'添加' + dialogtext"
      :visible.sync="addDialogFormVisible"
      width="30%"
      @close="addFormClose"
    >
      <el-form
        :model="addForm"
        label-width="120px"
        ref="addFormRef"
        :rules="addFormRules"
      >
        <el-form-item :label="dialogtext + '名称 :'" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改参数/属性对话框 -->
    <el-dialog
      :title="'修改' + dialogtext"
      :visible.sync="editDialogFormVisible"
      width="30%"
      @colse="editDialogColse"
    >
      <el-form
        :model="editForm"
        label-width="120px"
        ref="editFormRef"
        :rules="editFormRules"
      >
        <el-form-item :label="dialogtext + '名称 :'" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsPut">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 商品分类数据
      cateList: [],
      // props指定的规则
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        chilren: 'chilren',
        expandTrigger: 'hover'
        // checkStrictly:true,
      },
      // 级联选择器id
      selectKeys: [],
      // 当前tabname
      activeName: 'many',
      // 动态参数数据
      manyTableData: [],
      // 静态参数数据
      onlyTableData: [],
      // 添加参数/属性对话框显示隐藏
      addDialogFormVisible: false,
      // 添加参数/属性对话框表单数据
      addForm: {
        attr_name: ''
      },
      // 对话框表单验证规则
      addFormRules: {
        attr_name: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      },
      // 修改参数对话框显示隐藏
      editDialogFormVisible: false,
      // 修改参数表单
      editForm: {
        attr_name: ''
      },
      // 修改用户表单验证规则
      editFormRules: {
        attr_name: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 发起获取商品分类请求
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败')
      }
      this.$message.success('获取商品分类数据成功')
      this.cateList = res.data
    },
    // 获取动态或静态函数
    async getParamsDate() {
      if (this.selectKeys.length !== 3) {
        this.selectKeys = []
        return
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户分类信息失败')
      }
      console.log(res)
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(res)
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 级联选择器change事件
    handleChange() {
      if(this.selectKeys.length !== 3){
        this.selectKeys=[]
      }
        this.manyTableData=[]
        this.onlyTableData=[]
        this.getParamsDate()
    },
    // tab栏切换事件
    handleClick() {
      this.getParamsDate()
    },
    // 对话框关闭事件
    addFormClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 发起修改动态参数/静态属性请求
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          { attr_name: this.addForm.attr_name, attr_sel: this.activeName }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加该商品信息失败')
        }
        this.$message.success('添加商品信息成功')
        this.addDialogFormVisible = false
        this.getParamsDate()
      })
    },
    // 根据id获取当前商品参数/属性
    async editParams(id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${id}`,
        { attr_sel: this.activeName }
      )
      if (res.meta.status !== 200) {
        return this.$message.erroer('获取该参数失败')
      }
      this.$message.success('获取参数成功')
      this.editForm = res.data
      this.editDialogFormVisible = true
    },
    // 发起修改当前商品参数/属性请求
    async editParamsPut() {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
        {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName,
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('修改商品信息失败')
      }
      this.$message.success('修改商品信息成功')
      this.editDialogFormVisible = false
      this.getParamsDate()
      console.log(this.editForm)
    },
    editDialogColse() {
      this.$refs.editFormRef.resetFields()
    },
    // 删除参数/属性事件
    async deleteParams(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${id}`
      )
      if (res.meta.status !== 200) {
        console.log(res)
        console.log(id)
        return this.$message.error('删除该信息失败')
      }
      this.$message.success('删除该信息成功')
      this.getParamsDate()
    },
    // 文本框按下回车或失去焦点事件
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputVisible = false
      this.saveTagInput(row)
    },
    // 发起修改tag标签请求
    async saveTagInput(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(' '),
        }
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('添加标签失败')
      }
      this.$message.success('添加标签成功')
      row.inputValue = ''
    },
    handleClose(row, i) {
      console.log(row)
      row.attr_vals.splice(i, 1)
      console.log(row)
      this.saveTagInput(row)
    },
    // 点击按钮显示文本输入框
    showInput(row) {
      row.inputVisible = true
      //  当页面元素重新渲染触发该回调函数中的方法
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 发起修改当前商品参数/属性请求
    async editParamsPut() {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
        {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('修改商品信息失败')
      }
      this.$message.success('修改商品信息成功')
      this.editDialogFormVisible = false
      this.getParamsDate()
      console.log(this.editForm)
    },
    editDialogColse() {
      this.$refs.editFormRef.resetFields()
    },
    // 删除参数/属性事件
    async deleteParams(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${id}`
      )
      if (res.meta.status !== 200) {
        console.log(res)
        console.log(id)
        return this.$message.error('删除该信息失败')
      }
      this.$message.success('删除该信息成功')
      this.getParamsDate()
    },
    // 文本框按下回车或失去焦点事件
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputVisible = false
      this.saveTagInput(row)
    },
    // 发起修改tag标签请求
    async saveTagInput(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('添加标签失败')
      }
      this.$message.success('添加标签成功')
      row.inputValue = ''
    },
    handleClose(row, i) {
      console.log(row)
      row.attr_vals.splice(i, 1)
      console.log(row)
      this.saveTagInput(row)
    },
    // 点击按钮显示文本输入框
    showInput(row) {
      row.inputVisible = true
      //  当页面元素重新渲染触发该回调函数中的方法
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  },
  //   计算属性 根据级联选择框的数组长度给添加参数按钮和添加属性按钮更换不同disabel属性值来决定禁用于选用
  computed: {
    isBtnDisabled() {
      if (this.selectKeys.length !== 3) {
        return true
      }
      return false
    },
    //   计算属性  获取selectKeys第三位id给页签获取数据提供id值
    cateId() {
      if (this.selectKeys.length === 3) {
        return this.selectKeys[2]
      }
      return null
    },
    // 计算属性 计算dialog对话框的title 和form-item的label值
    dialogtext() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>
<style lang="less" scoped>
.box-card {
  margin-top: 20px;
}
.cat_class {
  margin: 20px;
}
.el-table {
  margin-top: 20px;
}
.el-tag {
  margin: 10px 20px;
}
.input-new-tag {
  width: 200px;
}
</style>
